package com.mrjy.schooldiy.bo;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mrjy.common.entity.DiyVideoInfo;
import com.mrjy.common.entity.DiyVideoLableRel;
import com.mrjy.common.entity.PolyInfo;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.redis.RedisPool;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.common.util.PolyvTokenUtil;
import com.mrjy.common.util.PolyvUtil;
import com.mrjy.common.util.RedisUtil;
import com.mrjy.maintain.dao.ISchoolInfoDao;
import com.mrjy.maintain.dto.SchoolInfoDTO;
import com.mrjy.schooldiy.dao.IDiyVideoDao;
import com.mrjy.schooldiy.dao.IDiyVideoLableRelDao;
import com.mrjy.schooldiy.dto.DiyVideoInfoDTO;
import com.tencent.common.Util;

@Service("schoolVideoBo")
public class DiyVideoBo implements IDiyVideoBo{
	@Resource
	private ISchoolInfoDao schoolInfoDao;
	@Autowired
	private RedisPool redisPool;
	@Resource
	private IDiyVideoDao diyVideoDao;
	@Resource
	private IDiyVideoLableRelDao diyVideoLableRelDao ;

	@Override
	public Object querySource(DiyVideoInfo dInfo, HttpSession session) {
		Map< String, Object> map = new HashMap<String, Object>();
		//根据学校id查询保利卫视下的音视频目录id
		SchoolInfoDTO dto = null;
		if(null != dInfo.getSchoolId()){
			dto = schoolInfoDao.queryBySchoolId(dInfo.getSchoolId());
			if((dto.getIsDiy().equals(1) && dto.getCataid() != null)||(dto.getIsDiy().equals(1) && dto.getCatatree() != null)){
				try {
					Object data = null;
					if(dInfo.getType().equals("1")){//视频目录
						data = PolyvTokenUtil.querySource(dto.getCataid());
					}else{
						data = PolyvTokenUtil.querySource(dto.getCatatree());
					}
					map.put("data", data);
				} catch (CloneNotSupportedException e) {
					e.printStackTrace();
				}
			}else {
				map.put("code", 201);
				map.put("message", "当前学校没有相关存储目录");
			}
		}else {
			map.put("code", 201);
			map.put("message", "当前学校没有相关存储目录");
		}
		return map;
	}

	@Override
	public Object insertSourse(DiyVideoInfo dInfo, HttpSession session) {
		Map< String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo)session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser){
			map.put("err_code",-1);
			map.put("err_msg","用户未登录");
			return map;
		}
		if(null == dInfo.getPolyCode()){
			map.put("err_code",201);
			map.put("err_msg","资源code不能为空");
			return map;
		}
		if(null == dInfo.getName()){
			map.put("err_code",202);
			map.put("err_msg","资源名称不能为空");
			return map;
		}
		if(null == dInfo.getContent()){
			map.put("err_code",203);
			map.put("err_msg","资源内容不能为空");
			return map;
		}
		if(null == dInfo.getType()){
			map.put("err_code",204);
			map.put("err_msg","资源类型不能为空");
			return map;
		}
		if(null == dInfo.getFileSize()){
			map.put("err_code",205);
			map.put("err_msg","资源大小不能为空");
			return map;
		}
		if(null == dInfo.getDuration()){
			map.put("err_code",206);
			map.put("err_msg","资源时长不能为空");
			return map;
		}
		if(null == dInfo.getSchoolId()){
			map.put("err_code",207);
			map.put("err_msg","学校id不能为空");
			return map;
		}
		dInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
		dInfo.setPublishTime(new Timestamp(System.currentTimeMillis()));
		int count= diyVideoDao.insertSourse(dInfo);
		if(count > 0){
			
			//添加视频与标签关系
			for(Integer diyLableId : dInfo.getTypeIds()){
				DiyVideoLableRel rel =new DiyVideoLableRel() ;
				rel.setDiyLableId(diyLableId);
				rel.setDiyVideoId(dInfo.getId());
				diyVideoLableRelDao.insert(rel) ;
			}
			
			//添加缓存
			String polyInfoJson = "";
			PolyInfo polyInfo = new PolyInfo();
			/*安全处理判断缓存是否已经存在*/
			String diyVideoId = GlobalConstant.VIDEODIY_POLYV_URL+dInfo.getId();
			if(diyVideoId != null){
				redisPool.del(diyVideoId);
			}
			PolyInfo polyInfoVideo = (PolyInfo) PolyvUtil.queryUrlByVid(dInfo.getPolyCode());
			//封装成一个polyInfo
			if (polyInfoVideo!=null) {
				polyInfo.setMpvh(polyInfoVideo.getMpvh());
				polyInfo.setMpvl(polyInfoVideo.getMpvl());
				polyInfo.setMpvm(polyInfoVideo.getMpvm());
				polyInfo.setImgh(polyInfoVideo.getImgh());
				polyInfo.setImgl(polyInfoVideo.getImgl());
                polyInfo.setMpvFlag(polyInfoVideo.getMpvFlag());
                polyInfo.setHls_l(polyInfoVideo.getHls_l());
                polyInfo.setHls_m(polyInfoVideo.getHls_m());
                polyInfo.setHls_h(polyInfoVideo.getHls_h());
                polyInfo.setSeed(polyInfoVideo.getSeed());
                polyInfo.setDuration(polyInfoVideo.getDuration());
                polyInfo.setMp3(polyInfoVideo.getMp3());
            }
			if (dInfo.getType().equals("0")) {
                map.put("mp3", polyInfo.getMp3());
                map.put("mpvl", "");
                map.put("mpvm", "");
                map.put("mpvh", "");
            }
			polyInfoJson = JSONObject.fromObject(polyInfo).toString();
			if (polyInfoJson!=null) {
				redisPool.set(GlobalConstant.VIDEODIY_POLYV_URL+dInfo.getId(), JSONObject.fromObject(polyInfoJson).toString());
			}
			map.put("err_code",200);
			map.put("err_msg","资源插入成功");
		}else{
			map.put("err_code",400);
			map.put("err_msg","资源插入失败");
		}
		
		return map;
	}

	@Override
	public Object editeSource(DiyVideoInfo dInfo, HttpSession session) {
		Map< String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo)session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser){
			map.put("err_code",-1);
			map.put("err_msg","用户未登录");
			return map;
		}
		if(null == dInfo.getPolyCode()){
			map.put("err_code",201);
			map.put("err_msg","资源code不能为空");
			return map;
		}
		if(null == dInfo.getName()){
			map.put("err_code",202);
			map.put("err_msg","资源名称不能为空");
			return map;
		}
		if(null == dInfo.getContent()){
			map.put("err_code",203);
			map.put("err_msg","资源内容不能为空");
			return map;
		}
		if(null == dInfo.getType()){
			map.put("err_code",204);
			map.put("err_msg","资源类型不能为空");
			return map;
		}
		if(null == dInfo.getFileSize()){
			map.put("err_code",205);
			map.put("err_msg","资源大小不能为空");
			return map;
		}
		if(null == dInfo.getDuration()){
			map.put("err_code",206);
			map.put("err_msg","资源时长不能为空");
			return map;
		}
		if(null == dInfo.getSchoolId()){
			map.put("err_code",207);
			map.put("err_msg","学校id不能为空");
			return map;
		}
		DiyVideoInfoDTO diyVideoInfoDTOs = diyVideoDao.queryAuViSourceById(dInfo);
		if(dInfo.getPolyCode().equals(diyVideoInfoDTOs.getPolyCode()) == false){
			try {
				Object data = PolyvTokenUtil.deleteSource(diyVideoInfoDTOs.getPolyCode());
				JSONObject jsonObj = JSONObject.fromObject(data);
				if (jsonObj.get("code") != null && jsonObj.get("code").equals(200)) {
					map.put("err_message", "原资源删除成功");
				}
			} catch (CloneNotSupportedException e) {
				e.printStackTrace();
			}
		}
		int count= diyVideoDao.editeSource(dInfo);
		if(count > 0){
			//处理视频与标签中间表
			if(dInfo.getTypeIds() != null){
				//删除之前的记录
				diyVideoLableRelDao.deleteByDiyVideoId(dInfo.getId()) ;
				//重新添加
				for(Integer diyLableId : dInfo.getTypeIds()){
					DiyVideoLableRel rel = new DiyVideoLableRel();
					rel.setDiyLableId(diyLableId);
					rel.setDiyVideoId(dInfo.getId());
					diyVideoLableRelDao.insert(rel) ;
				}
			}
			//添加缓存
			String polyInfoJson = "";
			PolyInfo polyInfo = new PolyInfo();
			/*安全处理判断缓存是否已经存在*/
			String diyVideoId = GlobalConstant.VIDEODIY_POLYV_URL+dInfo.getId();
			if(diyVideoId != null){
				redisPool.del(diyVideoId);
			}
			PolyInfo polyInfoVideo = (PolyInfo) PolyvUtil.queryUrlByVid(dInfo.getPolyCode());
			//封装成一个polyInfo
			if (polyInfoVideo!=null) {
				polyInfo.setMpvh(polyInfoVideo.getMpvh());
				polyInfo.setMpvl(polyInfoVideo.getMpvl());
				polyInfo.setMpvm(polyInfoVideo.getMpvm());
				polyInfo.setImgh(polyInfoVideo.getImgh());
				polyInfo.setImgl(polyInfoVideo.getImgl());
                polyInfo.setMpvFlag(polyInfoVideo.getMpvFlag());
                polyInfo.setHls_l(polyInfoVideo.getHls_l());
                polyInfo.setHls_m(polyInfoVideo.getHls_m());
                polyInfo.setHls_h(polyInfoVideo.getHls_h());
                polyInfo.setSeed(polyInfoVideo.getSeed());
                polyInfo.setDuration(polyInfoVideo.getDuration());
                polyInfo.setMp3(polyInfoVideo.getMp3());
            }
			if (dInfo.getType().equals("0")) {
                map.put("mp3", polyInfo.getMp3());
                map.put("mpvl", "");
                map.put("mpvm", "");
                map.put("mpvh", "");
            }
			polyInfoJson = JSONObject.fromObject(polyInfo).toString();
			if (polyInfoJson!=null) {
				redisPool.set(GlobalConstant.VIDEODIY_POLYV_URL+dInfo.getId(), JSONObject.fromObject(polyInfoJson).toString());
			}
			map.put("err_code",200);
			map.put("err_msg","资源修改成功");
		}else{
			map.put("err_code",400);
			map.put("err_msg","资源修改失败");
		}
		
		return map;
	}

	@Override
	public Object txUpdateDisableFlag(DiyVideoInfo dInfo) {
		Map< String, Object> map = new HashMap<String, Object>();
		int row = diyVideoDao.updateDisableFlag(dInfo);
		if(row > 0){
			map.put("err_code", 200);
			map.put("err_msg", "修改成功");
		}else {
			map.put("err_code", 201);
			map.put("err_msg", "修改失败");
		}
		return map;
	}

	@Override
	public Object deleteSource(DiyVideoInfo dInfo, HttpSession session) {
		int count = 0;
		Map< String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser){
			map.put("err_code",-1);
			map.put("err_msg","用户未登录");
			return map;
		}
		try {
			List<DiyVideoInfoDTO> diyVideoInfo = diyVideoDao.querySourceByid(dInfo);
			for(DiyVideoInfoDTO diyVideoInfo2:diyVideoInfo){
				Object data =  PolyvTokenUtil.deleteSource(diyVideoInfo2.getPolyCode());
				JSONObject jsonObj = JSONObject.fromObject(data);
				if (jsonObj.get("code") != null && jsonObj.get("code").equals(200)) {
					int rows = diyVideoDao.deleteAVSource(diyVideoInfo2.getId());
					if(rows>0){
						count++;
					}
				}
			}
			if(count>0){
				map.put("err_code", 200);
				map.put("err_msg", "共删除"+count+"条数据");
			}else{
				map.put("err_code", 201);
				map.put("err_msg", "删除失败");
			}
			
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return map;
	}

	@Override
	public Object queryPageForPcSource(DiyVideoInfo dInfo, HttpSession session) {
		Map< String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser){
			map.put("err_code",-1);
			map.put("err_msg","用户未登录");
			return map;
		}
		int total = diyVideoDao.countAllSource(dInfo);
		if(total>0){
			List<DiyVideoInfoDTO> diyVideoInfoDTOs = diyVideoDao.queryPageForPcSource(dInfo);
			if(diyVideoInfoDTOs != null && diyVideoInfoDTOs.size()>0){
				map.put("err_code",200);
				map.put("rows",diyVideoInfoDTOs);
				map.put("total",total);
				map.put("err_msg","查询有数据");
				
			}else{
				map.put("err_code",200);
				map.put("rows",null);
				map.put("err_msg","查询无数据");
			}
		}else {
			map.put("err_code",200);
			map.put("rows",null);
			map.put("total",0);
			map.put("err_msg","查询无数据");
		}
		return map;
	}

	@Override
	public Object queryPageList(DiyVideoInfo dInfo, HttpSession session) {
		Map< String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser){
			map.put("err_code",-1);
			map.put("err_msg","用户未登录");
			return map;
		}
		List<DiyVideoInfoDTO> diyVideoInfoDTOs = diyVideoDao.queryPageList(dInfo);
		if(diyVideoInfoDTOs != null && diyVideoInfoDTOs.size()>0){
			map.put("err_code",200);
			map.put("rows",diyVideoInfoDTOs);
			map.put("err_msg","查询有数据");
			
		}else{
			map.put("err_code",200);
			map.put("rows",null);
			map.put("err_msg","查询无数据");
		}
		return map;
	}

	@Override
	public Object queryAuViSourceById(DiyVideoInfo dInfo, HttpSession session) {
		Map< String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser){
			map.put("err_code",-1);
			map.put("err_msg","用户未登录");
			return map;
		}
		DiyVideoInfoDTO diyVideoInfoDTOs = diyVideoDao.queryAuViSourceById(dInfo);
		if(diyVideoInfoDTOs != null){
            map.put("err_code", 0);
			map.put("err_msg", "查询成功");
            //查询poly视频接口相关信息
            PolyvTokenUtil tokenUtil = null;
            try {
            	if(diyVideoInfoDTOs.getType().equals("0")){//音频
            		tokenUtil = PolyvTokenUtil.cloneSimplePolyInfo(null,diyVideoInfoDTOs.getPolyCode(), 
                            Util.getHostIp(Util.getInetAddress()),
                            "33852", "123", "1225");//"33852"loginUser.getId().toString()
            	}else if(diyVideoInfoDTOs.getType().equals("1")){//视频
            		tokenUtil = PolyvTokenUtil.cloneSimplePolyInfo(diyVideoInfoDTOs.getPolyCode(), null,
                            Util.getHostIp(Util.getInetAddress()),
                            "33852", "123", "1225");
				}
                
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
                return "error";
            }

            PolyInfo polyInfo = RedisUtil.cacheDIYVideoOrAudio(diyVideoInfoDTOs.getId() + "",diyVideoInfoDTOs.getPolyCode());
            map.put("mpvl", polyInfo.getMpvl());
            map.put("mpvm", polyInfo.getMpvm());
            map.put("mpvh", polyInfo.getMpvh());
            map.put("imgl", polyInfo.getImgl());
            map.put("imgh", polyInfo.getImgh());
            map.put("mpvFlag", polyInfo.getMpvFlag());
            map.put("hls_l", polyInfo.getHls_l());
            map.put("hls_m", polyInfo.getHls_m());
            map.put("hls_h", polyInfo.getHls_h());
            map.put("ts", tokenUtil.getTs());
            map.put("sign", tokenUtil.getSign());

            if (diyVideoInfoDTOs.getType().equals("0")) {
                map.put("mp3", polyInfo.getMp3());
                map.put("mpvl", "");
                map.put("mpvm", "");
                map.put("mpvh", "");
            }
            map.put("videoInfo", diyVideoInfoDTOs);
		}else{
			map.put("err_code",200);
			map.put("rows",null);
			map.put("err_msg","查询无数据");
		}
		return map;
	}

	@Override
	public Object addAuViViewNum(DiyVideoInfo dInfo, HttpSession session) {
		Map< String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(loginUser == null){
			map.put("err_code",-1);
			map.put("err_msg","用户未登录");
			return map;
		}
		int count = diyVideoDao.addAuViViewNum(dInfo.getId()); 
		if(count > 0){
			map.put("err_code",200);
			map.put("err_msg","增加成功");
		
		}else {
			map.put("err_code",201);
			map.put("err_msg","增加失败");
		}
		
		return map;
	}

	@Override
	public Object deleteSourceByCode(DiyVideoInfo dInfo, HttpSession session) {
		Map< String, Object> map = new HashMap<String, Object>();
		try {
			Object data = PolyvTokenUtil.deleteSource(dInfo.getPolyCode());
			map.put("data", data);
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return map;
	}

}
